package com.gitee.chili.leisure.api.member;

import com.gitee.chili.leisure.ResponseResult;
import com.gitee.chili.leisure.annotation.PathRestController;
import com.gitee.chili.leisure.domain.Member;
import com.gitee.chili.leisure.domain.dto.LoginQuery;
import com.gitee.chili.leisure.domain.dto.MemberVo;
import com.gitee.chili.leisure.service.IMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;

import javax.validation.Valid;
import java.util.Objects;
import java.util.Optional;

/**
 * MemberController
 *
 * @author week solider
 * @since 2020.09.01
 */
@Validated
@PathRestController("/member")
public class MemberController {

    @Autowired
    private IMemberService memberService;

    @PostMapping("/login")
    public ResponseResult<MemberVo> login(@Valid LoginQuery login) {

        Member member = null;

        // 手机号: 0   用户名: 1   token: 2
        switch (login.getLoginWay()) {
            case 0:
                Integer code = login.getCode();
                if (Objects.isNull(code)) {
                    return ResponseResult.failure("请填写验证码");
                }

                // TODO 验证验证码
                if (!code.equals(123456)) {
                    return ResponseResult.failure("验证码错误");
                }

                member = memberService.query(login.getPhone().toString());
                break;
            case 1:
                member = memberService.query(login.getUsername(), login.getPassword());
                break;
            case 2:
                Optional<Member> optional = memberService.findById(Long.parseLong(login.getToken()));
                member = optional.orElse(null);
                break;
        }

        if (Objects.nonNull(member)) {
            // 是否是断线重连
            MemberVo vo = memberService.builder(member);
            return ResponseResult.success(vo);
        }

        return ResponseResult.failure("用户不存在");
    }

    @PostMapping("/memberInfo")
    public ResponseResult<Member> memberResponseResult(@Valid Long userId) {

        Optional<Member> optional = memberService.findById(userId);
        if (optional.isPresent()) {
            return ResponseResult.success(optional.get());
        }
        return ResponseResult.failure("用户不存在");
    }

    @PostMapping("/get")
    public ResponseResult<Member> getMember(Long memberId) {
        Optional<Member> optional = memberService.findById(memberId);
        return optional.isPresent() ? ResponseResult.success(optional.get()) : ResponseResult.failure("玩家不存在");
    }
}
